package com.heima.listener;

import com.heima.api.PayClient;
import com.heima.constants.MQConstants;
import com.heima.domain.po.Order;
import com.heima.dto.PayOrderDTO;
import com.heima.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {

    private final IOrderService iOrderService;

    private final PayClient payClient;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = MQConstants.DELAY_ORDER_QUEUE_NAME),
                    exchange = @Exchange(name = MQConstants.DELAY_EXCHANGE_NAME,delayed = "true",type = ExchangeTypes.DIRECT),
                    key = MQConstants.DELAY_ORDER_KEY
            )
    )
    public void listenOrderDelayMessage(Long orderId){
        // 1.查询订单
        Order order = iOrderService.getById(orderId);
        // 2.检测订单状态是否存在，再判断是否已支付
        if(order != null || order.getStatus() != 1){
            // 如果订单不存在或者已支付
            return;
        }
        // 3.未支付，需要查询支付流水状态
        PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(orderId);
        // 4.判断是否支付
        if(payOrderDTO.getStatus() == 3){
            // 4.1.已支付，标记订单状态为已支付
            System.out.println("11111111111111111111111----"+orderId);
            iOrderService.markOrderPaySuccess(orderId);
        }else {
            //4.2.未支付，取消订单，回复库存
            System.out.println("222222222222222222222222----"+orderId);
            iOrderService.cancelOrder(orderId);
        }
    }
}
